package com.dmall.play.interview.chapter09;

/**
 * 记忆化搜索
 * @author xiao1.wang
 * @date 2021-01-20 10:07:45
 */
public class Leetcode64V5 {

    private int[][] dp;

    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int row = grid.length;
        int col = grid[0].length;
        dp = new int[row][col];
        for (int i = row - 1; i >= 0; i--) {
            for (int j = col - 1; j >= 0; j--) {
                if (i == row -1 && j == col - 1) {
                    dp[i][j] = grid[i][j];
                } else if (i == row - 1) {
                    dp[i][j] = dp[i][j + 1] + grid[i][j];
                } else if (j == col - 1) {
                    dp[i][j] = dp[i + 1][j] + grid[i][j];
                } else {
                    dp[i][j] = Math.min(dp[i + 1][j], dp[i][j + 1]) + grid[i][j];
                }
            }
        }
        return dp[0][0];
    }

    public static void main(String[] args) {
        Leetcode64V5 leetcode64 = new Leetcode64V5();
        int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
        // int[][] grid = {{1, 2}, {1, 1}};
        System.out.println(leetcode64.minPathSum(grid));
    }
}
